#pragma once
#include "nocopy.hpp"
#include "Log.hpp"
#include "comm.hpp"
#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "InetAddr.hpp"
#include<functional>

//const std::string default_ip = "0.0.0.0";
const uint16_t default_port = 8888;
const int default_sockfd = -1;
const int default_bufferSize = 1024;

//定义函数类型
using cb_t =std::function<std::string(std::string)>;

class UdpServer : public nocopy
{
public:
    // UdpServer(const std::string &ip = default_ip, uint16_t port = default_port)
    //     : _ip(default_ip), _port(default_port), _sockfd(default_sockfd)
    // {
    // }

    UdpServer(cb_t onMessage ,uint16_t port = default_port)
        : On_Message(onMessage) ,_port(default_port), _sockfd(default_sockfd)
    {
    }

    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            lg.LogMessage(Fatal, "socket error,%d : %s\n", errno, strerror(errno));
            exit(Socket_error);
        }
        lg.LogMessage(Info, "socket is created ,socketfd %d\n", _sockfd);

        // 创建网络信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        //服务器ip由系统绑定
        //local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr =INADDR_ANY;

        // 绑定到网络
        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n != 0)
        {
            lg.LogMessage(Fatal, "socoket bind error,%d : %s\n", errno, strerror(errno));
            exit(Bind_error);
        }

        lg.LogMessage(Info, "socket init over...\n");
    }

    void Start()
    {
        char buffer[default_bufferSize];
        // 启动了就不会停下
        while (true)
        {
            // 获取对方的信息
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 默认为字符串
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                // 转发功能
                InerAddr addr(peer);
                buffer[default_bufferSize] = 0;
                std::string response=On_Message(buffer);
                //std::cout <<"[" <<addr.PrintDebug()<<"]"<< buffer << std::endl;
                
                sendto(_sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
    }
    ~UdpServer()
    {
        
    }

private:
    //std::string _ip;
    uint16_t _port;
    int _sockfd;

    cb_t On_Message;//回调
};
